package com.project.web.admin.utils.captcha;

import com.octo.captcha.Captcha;
import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.yun.common.utils.redis.RedisConsts;

import java.util.Locale;

/**
 * Created by Administrator on 2016/4/11.
 */
@Component
public class RedisCaptchaService extends DefaultManageableImageCaptchaService {

    protected RedisCaptchaStore store = new RedisCaptchaStore();

    @Bean
    public CaptchaEngine captchaEngine(){
        return new CaptchaEngine();
    }

    public Object getChallengeForID(String id) throws CaptchaServiceException {
        return this.getChallengeForID(RedisConsts.ADMIN_REDIS_CAPTCHA_KEY + id, Locale.getDefault());
    }

    public Object getChallengeForID(String id, Locale locale) throws CaptchaServiceException {
        Captcha captcha = this.generateAndStoreCaptcha(locale, id);
        return this.getChallengeClone(captcha);
    }

    public Boolean validateResponseForID(String id, Object response) throws CaptchaServiceException {
        id = RedisConsts.ADMIN_REDIS_CAPTCHA_KEY + id;
        if (!this.store.hasCaptcha(id)) {
            throw new CaptchaServiceException("Invalid ID, could not validate unexisting or already validated captcha");
        } else {
            Boolean valid = this.store.getCaptcha(id).validateResponse(response);
            this.store.removeCaptcha(id);
            return valid;
        }
    }

    protected Captcha generateAndStoreCaptcha(Locale locale, String id) {
        Captcha captcha = super.engine.getNextCaptcha();
        this.store.storeCaptcha(id, captcha, locale);
        return captcha;
    }

}
